import { Config } from 'config.js';
import { Token } from 'token.js';

class Base{

  constructor(){
    this.baseRequestUrl = Config.requestUrl;
  }

  // 获取event参数
  getDataSet(event,key){
    return event.currentTarget.dataset[key];
  }

  request(params,noRefetch=false){
    var that = this;
    var url = this.baseRequestUrl + params.url;
    if(!params.method){
      params.method = 'GET';
    }
    wx.request({
      url: url,
      method: params.method,
      data: params.data,
      header: {
        'content-type':'application/json',
        'token': wx.getStorageSync('token'),
      },
      success(res){
        var code = res.statusCode.toString();
        var startChar = code.charAt(0);
        if(startChar == '2'){
          params.sCallBack && params.sCallBack(res.data);
        }else{
          if(code == '401'){
            if (!noRefetch){
              that._refetch(params);
            }
            if(noRefetch){
              params.eCallback && params.eCallback(res.data);
            }
          }
        }
      },fail(err){
        console.log(err);
      }
    })
  }

  // 重新请求Url地址获取token
  _refetch(params){
    var token = new Token();
    token._getTokenFormServer((token)=>{
      this.request(params,true);
    });
  }

}

export {Base};